//
//  QianTangViewController.m
//  DongChiDaChiProject1
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "QianTangViewController.h"
#import "MJRefresh.h"
#import "DataHandle.h"
#import "TongYongDeCellTableViewCell.h"
#import "DetailUIViewController.h"
#import "UserManager.h"

@interface QianTangViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

// 记录下拉的次数
@property (nonatomic, assign) int pullCount;

// 记录是否是程序刚开始
@property (nonatomic, assign) int isGangKaiShi;

// 判断是否请求数据
@property (nonatomic, assign) BOOL isEndRequestData;

@end

@implementation QianTangViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"靓汤";
    self.view.backgroundColor = [UIColor whiteColor];
    // 添加tableView
    [self addTableView];
    [self searchNet];
    _pullCount = 0;
    _isGangKaiShi = 0;
    _isEndRequestData = NO;
    self.tabBarController.tabBar.hidden = YES;
    [[DataHandle shareHandle] deleteQianTangSaveArray];
     // [[NSNotificationCenter defaultCenter] postNotificationName:@"HIDDENTABBAR" object:nil];
    [self addBar];
}


#pragma mark - 添加网络检测
- (void)searchNet
{
    NSLog(@"wangluo = %@", [[UserManager shareUserManagerHandle] getNet]);
    
    if ([[[UserManager shareUserManagerHandle] getNet] isEqualToString:@"NO"]) {
        // 网络不通
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"警告" message:@"该软件只有在网络状态下才能使用" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:alertAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    } else {
        // 上下啦刷新
        [self pullRefresh];
    }
}


#pragma mark - 添加bar
- (void)addBar
{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(returnToLast:)];
    leftItem.tintColor = [UIColor colorWithHue:0.8 saturation:1 brightness:0.7 alpha:1];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    [self.navigationController.navigationBar setTranslucent:NO];
}

- (void)returnToLast:(UIBarButtonItem *)barItem
{
 [self.navigationController popViewControllerAnimated:YES];
}

- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor colorWithHue:1 saturation:0 brightness:1 alpha:0.5];
    //self.tableView.separatorColor = [UIColor redColor];
    [self.view addSubview:_tableView];
    
    
    
    
}

- (void)pullRefresh
{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(xialaRefresh)];
    self.tableView.footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(shanglaRefresh)];
    [self.tableView.header beginRefreshing];
    
}

#pragma mark - 下拉刷新
- (void)xialaRefresh
{
    // 建立数据源
    if (_isGangKaiShi == 0) {
        
        [[DataHandle shareHandle] requestQiangTangDataWithPage:1 AndReturn:^(NSMutableArray *array) {
            NSLog(@"count = %ld", (unsigned long)array.count);
            _pullCount = 1;
            _isEndRequestData = YES;
            [self.tableView reloadData];
            
        }];
        _isGangKaiShi = 1;
    }
   
    [self.tableView.header endRefreshing];
}
#pragma mark - 上啦刷新
- (void)shanglaRefresh
{
//    _pullCount++;
    NSLog(@"_pullCount = %d", _pullCount);
    switch (_pullCount) {
        case 1:
        {
            if (_isEndRequestData == YES) {
                [[DataHandle shareHandle] requestQiangTangDataWithPage:2 AndReturn:^(NSMutableArray *array) {
                    NSLog(@"count = %ld", (unsigned long)array.count);
                    _pullCount = 2;
                    _isEndRequestData = YES;
                    [self.tableView reloadData];
                    
                }];
                // block的执行速度小于这句话的执行速度
                _isEndRequestData = NO;
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"您不要狂拉本页面哦！吃吃正在为您努力加载数据" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alert show];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [alert dismissWithClickedButtonIndex:0 animated:YES];
                });
            }
            
            break;
        }
        case 2:
        {
            if (_isEndRequestData == YES) {
                [[DataHandle shareHandle] requestQiangTangDataWithPage:3 AndReturn:^(NSMutableArray *array) {
                    NSLog(@"count = %ld", (unsigned long)array.count);
                    _pullCount = 3;
                    _isEndRequestData = YES;
                    [self.tableView reloadData];
                    
                }];
                _isEndRequestData = NO;
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"您不要狂拉本页面哦！吃吃正在为您努力加载数据" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alert show];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [alert dismissWithClickedButtonIndex:0 animated:YES];
                });
            }
            break;
        }
           case 3:
        {
            if (_isEndRequestData == YES) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"目前还没有新的哦！" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alertView show];
                // alertView消失
                [self performSelector:@selector(dismissAlertView:) withObject:alertView afterDelay:1.0];
            }
           
            break;
        }
            
       
            
        default:
       
            break;
    }

    
    [self.tableView.footer endRefreshing];
}

- (void)dismissAlertView:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark - 必须写的两个方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[DataHandle shareHandle] returnCountOfQiangTangModel];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"TongYongDeCellTableViewCell";
    TongYongDeCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[TongYongDeCellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.qianTangModel = [[DataHandle shareHandle] returnQiangTangModelByIndex:indexPath];
  //  cell.backgroundColor = [UIColor colorWithHue:0 saturation:1 brightness:1 alpha:0.1];
    cell.backgroundColor = [UIColor colorWithHue:0.7 saturation:0.5 brightness:1 alpha:0.1];
  
        return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 170 * kHeightFitParameter;
}

#pragma mark - 点击时间
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"靓汤indexPath.section = %ld, row = %ld", (long)indexPath.section, indexPath.row);
    DetailUIViewController *detailVC = [[DetailUIViewController alloc] init];
    detailVC.meiZhouModel = (MeiZhouModel *)[[DataHandle shareHandle] returnQiangTangModelByIndex:indexPath];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:detailVC];
    [self presentViewController:naVC animated:YES completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
